package com.rd.student.ruanjian.class4.zhangrui.week4;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

public class RandomName {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        List<String> classmates = new ArrayList<>();
        // 从文件中读取班级所有同学的名字
        File file = new File("all.txt");
        //写入随机的同学的姓名
        FileWriter filename=new FileWriter( "randoms.txt");
        BufferedWriter writer=new BufferedWriter(filename);
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String str;
        while ((str = reader.readLine()) != null) {
            classmates.add(str);
        }
        reader.close();
        while (true) {
            System.out.print("请输入要随机选取的同学个数：" +"\n" + "输入“0”结束选取");
            int n = scanner.nextInt();
            if (n == 0) return;
            if (n > classmates.size()) {
                System.out.println("输入的个数大于班级总人数！请重新输入");

            } else {
                List<String> randomNames = getRandomNames(classmates, n);
                System.out.println("随机选取的同学名字为：");
                for (String name : randomNames) {
                    System.out.println(name);
                }
                // 将随机名字写入文件
                for (String name : randomNames) {
                    writer.write(name);
                    writer.newLine();
                }
               writer.close();
            }
            }
        }




    private static List<String> getRandomNames(List<String> names, int n) {
        Random random = new Random();
        List<String> randomNames = new ArrayList<>();

        while (randomNames.size() < n) {
            String name = names.get(random.nextInt(names.size()));
            if (!randomNames.contains(name)) {
                randomNames.add(name);
            }
        }

        return randomNames;
    }
}
